#include "tcpServer.hpp"
#include "protocol.hpp"
#include <thread>

#define DEFAULTPORT 8888
class HTTPServer
{
private:
    int _port;
    int _listen_sock;
    bool _stop;
    TcpServer *_tcp_server;

public:
    HTTPServer(int port = DEFAULTPORT)
        : _port(port), _tcp_server(nullptr), _stop(false)
    {}

    void Init()
    {
        _tcp_server = &TcpServer::GetInstance(_port);
        _tcp_server->InitServer();
    }
    void Start()
    {
        int listen_sock = _tcp_server->Sock();
        while (!_stop)
        {
            struct sockaddr_in peer; //服务端 用来接收 客户端的信息结构【获知请求方的信息】
            memset(&peer, 0, sizeof(peer));
            socklen_t len = sizeof(peer);
            int work_sock = accept(listen_sock, (struct sockaddr*)&peer, &len);
            if(work_sock < 0)
                continue;  //若某次获取连接失败，执行下一轮获取即可【不能因为一个连接失败就使得服务器关闭】
            /*
                获取到了新连接，创建新线程 去执行相关作用函数
            */
           printf("TEST:: accept2\n");
           //int *sock = new int(work_sock); // ? 暂时方案 防止线程修改了work_sock
           
           std::thread t1(ThreadEntry::HanderRequest, work_sock);
           t1.detach();
        }
    }

    ~HTTPServer()
    {
    }
};